import { Key, useEffect, useRef, useState } from "react";
import { flatObjArr, getArrayValues } from "../../common/utils";
import { CHECK_TYPE, DEFAULT_ROW_KEY, IMUIColumnType, IMUITable, SELECTION_COL_WITH } from "./common";

// 表格 展开收起、选中、排序等逻辑处理
export const useTable = (props: IMUITable) => {
    const { data, rowKey = DEFAULT_ROW_KEY, expandable, getRowDisabled, selRow, setSelRow, onChange } = props
    const [expandedKeys, setExpandedRowKeys] = useState<any>([]);
    const expandedRowKeys = expandable?.expandedRowKeys || expandedKeys
    const onExpandedRowsChange = expandable?.onExpandedRowsChange || setExpandedRowKeys
    const { selectedRowKeys, onChange: onSelRowKeysChange } = props.rowSelection || {}
    // 表头排序信息
    const [sortInfo, onSortInfoChange] = useState<any[]>([])
    // 用于判断 判断是否第一次初始化数据 为tru表示已经初始化过数据
    const initFlag = useRef(false);

    const setSortInfo = (newValue: any[]) => {
        onSortInfoChange(newValue)
        onChange?.(undefined, undefined, newValue)
    }

    const allRowKeys = getArrayValues(data || [], rowKey);

    // 第一次获取到数据时 展开所有行
    useEffect(() => {
        if (!data?.length || initFlag.current) return;
        const allRowKeys = getArrayValues(data || [], rowKey);
        onExpandedRowsChange(allRowKeys);
        initFlag.current = true;
    }, [data]);

    const onSelectRow = (record: any, e?: React.MouseEvent<any, MouseEvent>) => {
        if (!setSelRow) return
        if (e) e.stopPropagation();
        if (getRowDisabled && getRowDisabled(record)) return;
        setSelRow(record);
    };

    // 复选框相关方法
    const rowSelection = props.rowSelection ? {
        columnWidth: SELECTION_COL_WITH,
        ...props.rowSelection,
        // 某一行是否被选中  不传row表示全选框
        getRowChecked: (row?: any) => {
            if (!row) {
                if (!selectedRowKeys?.length) return CHECK_TYPE.NOT_CHECKED
                if (selectedRowKeys?.length === allRowKeys.length) return CHECK_TYPE.CHECKED
                return CHECK_TYPE.HALF_CHECKED
            }
            if (selectedRowKeys?.includes(row[rowKey])) return CHECK_TYPE.CHECKED
            if (row.children?.length && flatObjArr(row.children).some((item) => selectedRowKeys?.includes(item[rowKey]))) return CHECK_TYPE.HALF_CHECKED
            return CHECK_TYPE.NOT_CHECKED
        },
        // 选择某一行
        onRowCheck: (row?: any) => {
            if (!row) {
                if (selectedRowKeys?.length === allRowKeys.length) {
                    onSelRowKeysChange?.([], [], { type: "none" })
                } else {
                    onSelRowKeysChange?.(allRowKeys, flatObjArr(data), { type: "all" })
                }
            } else {
                const tmp = [...(selectedRowKeys || [])]
                const checked = !tmp?.includes(row[rowKey])
                // 当前行及其子孙行
                const rows = flatObjArr([row])
                rows.forEach((item) => {
                    const i = tmp?.indexOf(item[rowKey])
                    if (checked && i === -1) tmp.push(item[rowKey])
                    if (!checked && i !== -1) tmp.splice(i, 1)
                });
                // 判断上级是否选中
                flatObjArr(data).reverse().forEach((item) => {
                    const allChildren = flatObjArr(item.children)
                    // 当前行在该行下级
                    if (allChildren.find((r) => r[rowKey] === row[rowKey])) {
                        const i = tmp?.indexOf(item[rowKey])
                        if (checked && i === -1 && allChildren.every((r) => tmp?.includes(r[rowKey]))) tmp.push(item[rowKey])
                        if (!checked && i !== -1 && allChildren.some((r) => !tmp?.includes(r[rowKey]))) tmp.splice(i, 1)
                    }
                })
                const checkedRows = flatObjArr(data).filter((item: any) => tmp.includes(item[rowKey]))
                onSelRowKeysChange?.(tmp, checkedRows, { type: "multiple" })
            }
        },
    } : undefined

    // 排序
    const onSortChange = (column: IMUIColumnType) => {
        const { dataIndex, sortOrder, sorter } = column
        let newOrder = undefined
        if (!sortOrder) newOrder = "ascend"
        if (sortOrder === "ascend") newOrder = "descend"
        const sortItem = {
            column: {
                ...column,
                sortOrder: newOrder,
            },
            field: dataIndex,
            order: newOrder,
        }
        // 不允许多列排序
        if (typeof sorter !== 'object' || !sorter?.multiple) return setSortInfo([sortItem])
        const tmp = sortInfo.filter((item) => item.field !== dataIndex)
        if (!newOrder) return setSortInfo(tmp)
        setSortInfo([
            ...tmp,
            sortItem
        ])
    }

    return {
        rowSelection,
        expandedRowKeys,
        onExpandedRowsChange,
        onSelectRow,
        onSortChange
    }
}

export const getNewExpandKeys = (expandedRowKeys: Key[], record: any, rowKey = DEFAULT_ROW_KEY) => {
    const itemKey = record[rowKey]
    const tmp = [...expandedRowKeys]
    const i = expandedRowKeys.findIndex((item: Key) => item === itemKey)
    if (i === -1) {
        tmp.push(itemKey)
    } else {
        tmp.splice(i, 1)
    }
    return tmp
}
